package org.zoomdev.zoom.lock.modules;

import org.zoomdev.zoom.aop.Interceptor;
import org.zoomdev.zoom.aop.Invoker;
import org.zoomdev.zoom.ioc.impl.factories.ParameterAdapterFactory;
import org.zoomdev.zoom.lock.LockExecutor;

import java.lang.reflect.Method;

public class LockInterceptor implements Interceptor {
    private final String format;
    private final ParameterAdapterFactory.ParameterAdapter[] adapters;

    private final LockExecutor executor;

    public LockInterceptor(String format, ParameterAdapterFactory.ParameterAdapter[] adapters, LockExecutor executor) {
        this.format = format;
        this.adapters = adapters;
        this.executor = executor;
    }

    @Override
    public Object intercept(Invoker invoker, Method method, Object target, Object[] args) throws Throwable {
        String[] values = ParameterAdapterFactory.getValues(adapters, args);
        String key = String.format(format, (Object[]) values);
        return executor.execute(key, () -> invoker.invoke(target, args));

    }
}
